var proof = require('../../utils/proof.js');
var constract = require('../../utils/constract.js');
var app = getApp();
var cardId;

Page({
  data: {
    flag: true,
    mes: '获取验证码',
    num:0,
    seximg:false,
    text:false,
    yzm: false,
    imgUrl: '',
    across: true,
    avatar: '',
    inpDisabled: true,
    oldPhone: '',
    change: 0,
    disCompany: true
  },

  onLoad: function (options) {
    console.log(options);

    var that = this;
    cardId = options.cardId;

    app.Verification(function (token) {

      wx.request({
        url: constract.index, //判断存在当前用户信息
        header: { token: token },
        success: function (res) {
          console.log(res);
          var gender, change;
          res.data.data.user.length>0 ? gender = res.data.data.user[0].gender  
                                      : gender = 2;  
          
          res.data.data.user.length>0 ? change = 0 : change = 1;

          if(res.data.data.user.length>0) {
            wx.request({
              url: constract.findByUid,
              header: {token: token},
              success: (res)=>{
                // console.log(res);
                // console.log('----findByUid----');
                that.setData({
                  avatar: res.data.avatar
                })
              },
              fail: (err)=>{
                console.log(err)
              }
            })
          } else {
            wx.request({
              url: constract.defaultName,
              header: {token: token},
              success: (res)=>{
                // console.log(res);
                // console.log('----defaultName----');
                that.setData({
                  avatar: res.data.avatar
                })
              },
              fail: (err)=>{
                console.log(err)
              }
            })
          }

          that.setData({
            regState: res.data.data.state,
            gender: gender,
            change:change,
          })
        }
      })

    })

    wx.getSystemInfo({
      success: function (res) {
        var abc = res.system.substr(0, 3);
        if (abc == "iOS") {
          that.setData({
            text: true,
            seximg:true
          })
        }
      },
    });

    this.setData({
      userInfo: options,
      oldPhone: options.phone || '',
    })

  },
  phone: function (e) {
    this.data.phone = e.detail.value;
  },
  code: function (e) {
    this.data.code = e.detail.value;
  },
  yzmcode: function (e) {
    this.data.yzmcode = e.detail.value;
  },
  bindinput: function (e) {
    var txt = e.detail.value;
    this.setData({
      num: txt.length
    })
  },
  bindcode: function () {

    var phone = this.data.phone;
    if (!proof.isMobile(phone)) {
      wx.showModal({
        title: '提示',
        content: '请输入正确的手机号',
        showCancel: false
      });
      return;
    };

    this.setData({
      yzm: true,
      across: true,
      phone: phone,
      imgUrl: constract.verifyCode + '?capName=' + phone + '&t=' + new Date().getTime()
    })
  },
  confirm: function () {//点击确定
    var that = this;
    var phone = this.data.phone;
    var yzmcode = this.data.yzmcode;
    wx.request({
      url: constract.sendCode,
      data: { phone: phone, captcha: yzmcode },
      success: function (res) {
        var contentTxt = res.data.msg;
        if (res.data.code == "12000") {
          if (wx.showToast) {
            wx.showToast({
              title: "验证码已发送",
              icon: "success",
              mask: true,
              duration: 2000
            })
          }
          that.setData({
            across: false
          })
          proof.settime(that);
        } else {
          if (wx.showModal) {
            wx.showModal({
              title: "提示",
              content: contentTxt,
              showCancel: false,
            })
          }
        }
      }
    })
    that.setData({
      yzm: false,
      across: false
    })
  },
  tipCode: function(){
    if (wx.showToast) {
      wx.showToast({
        title: "请先获取验证码！",
        icon: "none",
        mask: true,
        duration: 2000
      })
    }
  },
  recode: function (e) {//点击验证码更换
    var phone = this.data.phone;
    this.setData({
      imgUrl: constract.verifyCode + '?capName=' + phone + '&t=' + new Date().getTime()
    })
  },
  cancel: function () {//点击取消
    this.setData({
      yzm: false,
      across: false
    })
  },
  avatar:function(){
    var that=this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths[0];
        that.setData({
          avatar: tempFilePaths,
          uploadAvatar: true
        })
      }
    })
  },
  sex:function(e) {
    this.setData({
      gender:e.detail.value
    })
  },
  showCode: function(e){
    var phone = e.detail.value;
    var that = this;
    if(phone != this.data.oldPhone){
      this.setData({
        change: 1
      })
    }
  },
  companyTap: function(){
    var that = this;
    setTimeout(function(){
      that.setData({
        disCompany: false,
      })
    },800);
  },
  submit: function (e) {
    var data = e.detail.value;
    var name = data.name;
    var phone = data.phone;
    var code = data.code;
    var email = data.email;
    var company = data.company_name;
    
    var avatar = this.data.avatar;
    var uploadAvatar = this.data.uploadAvatar;

    var change = this.data.change;

    data.avatar = avatar;

    console.log(data);
    
    if(phone != this.data.oldPhone) {
      change = 1;
    }

    data.change = change;

    /******验证 start******/
    if (proof.trim(name) == '') {
      wx.showModal({
        title: '提示',
        content: '姓名不能为空',
        showCancel: false
      });
      return;
    };
    if (!proof.isMobile(phone)) {
      wx.showModal({
        title: '提示',
        content: '请输入正确的手机号',
        showCancel: false
      });
      return;
    };


    /*********************/
    if (!code && change == 1) {
      wx.showModal({
        title: '提示',
        content: '请获取验证码',
        showCancel: false
      });
      return;
    };
    if (proof.trim(company) == '') {
      wx.showModal({
        title: '提示',
        content: '公司不能为空',
        showCancel: false
      });
      return;
    };
    if (proof.trim(email) !== '') {
      if (!proof.isEmail(email)) {
        wx.showModal({
          title: '提示',
          content: '请输入正确的邮箱格式',
          showCancel: false
        });
        return;
      }
    };
    if (wx.showLoading) {
      wx.showLoading({
        title: '保存中',
        mask: true,
      });
    };
    /******验证 end******/

    app.Verification(function (token) {
      wx.request ({
        url: constract.isExist,
        header:{token:token},
        data: {company_name: company},
        success: (res)=>{
          console.log(res);
          cardId = res.data.data;
          if(+res.data.code === 13000){
            if (wx.hideLoading) {
              wx.hideLoading();
            };
            wx.showModal({
              title: '提示',
              content: '该名片信息已存在',
              confirmText: '修改',
              success: function(res) {
                console.log(res);
                if (res.confirm) {
                  wx.redirectTo({
                    url:'/pages/edit/edit?mycardid='+cardId,
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消');
                  return false;
                }
              }
            })
          } else if(+res.data.code === 12000) {
            //公司名不存在时再添加
            wx.request({
              url: constract.add,
              header:{token:token},
              data:data,
              success:function(res){
                console.log(res);
                if(res.data.msg=="验证码错误"){
                  wx.hideLoading();
                  wx.showModal({
                    title: '提示',
                    content: '验证码错误',
                    showCancel: false
                  });
                }else if(uploadAvatar){ //有头像的时候上传头像
                  wx.uploadFile({
                    url: constract.imgsUpdate,
                    header: { token: token },
                    formData: {cardId: res.data.data},
                    filePath: avatar,
                    name: "avatar",
                    complete:function(res){
                      if (wx.hideLoading) {
                        wx.hideLoading();
                      };
                      app.globalData.swiperIdx = 0;
                      wx.switchTab({
                        url: '/pages/index/index'
                      });
                    }
                  })
                } else {
                  if (wx.hideLoading) {
                    wx.hideLoading();
                  };
                  app.globalData.swiperIdx = 0;
                  wx.switchTab({
                    url: '/pages/index/index'
                  });
                }
                
              },
              fail:(err)=>{
                console.log(err);
              }
            })
            // app.globalData.getAuth = false;
          }
        },
        fail: (err)=>{
          console.log(err);
        }
      })

    })
    
  }
})